﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyLib;
using EPPLog;

namespace Billing2
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.AppendHeader("Cache-Control", "no-store");
            this.Response.AppendHeader("Cache-Control", "no-cache");
#if !DEV
            this.Response.AppendHeader("Content-Security-policy", "default-src https: data: 'unsafe-inline' 'unsafe-eval'");
#endif

            //anti CSRF
            if (!this.Page.IsPostBack)
            {
                string anti_csrf = ClsPasswordHelper.Encrypt("anti_csrf" + MyLib.Rand.RandomInt(0, int.MaxValue - 1).ToString()).Replace("=", "").Replace("/", "").Replace("+", "");
                this.request_id.Value = anti_csrf;
                this.Session["request_id"] = anti_csrf;
            }
            else
            {
                if (this.Session["request_id"] == null || this.request_id.Value != this.Session["request_id"].ToString())
                {
                    EPPLog.Logger.Error(Common.EscapeLog(String.Format("Detecterd CSRF1. RawUrl={0} request_id={1} inSession={2}", this.Request.RawUrl, this.request_id.Value, this.Session["request_id"])));
                    base.Response.Redirect("logout.aspx", true);
                    return;
                }
            }

            if (Request.Cookies["__LOGINCOOKIE__"] == null ||
                Request.Cookies["__LOGINCOOKIE__"].Value == "")
            {
                //At this point, we do not know if the session ID that we have is a new
                //session ID or if the session ID was passed by the client.
                //Update the session ID.
                Session.Abandon();

                HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", "");
                cookie.Secure = true;
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);
                //To make sure that the client clears the session ID cookie, respond to the client to tell
                //it that we have responded. To do this, set another cookie.
                Response.Redirect("~/Default.aspx");
                return;
            }

            EPPLog.Logger.Info("SessionID (after login): " + Session.SessionID);

            //Make sure that someone is not trying to spoof.
            string username = "";
            string password = "";
            try
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies["__LOGINCOOKIE__"].Value);
                if (ticket == null || ticket.Expired == true)
                    throw new Exception();
                RemoveRedirCookie();
                string data = ticket.UserData;
                data = System.Text.Encoding.ASCII.GetString(MyLib.HexUtility.HexToBytes(data));
                string[] ss = data.Split(new char[] { '|' });
                username = ss[0];
                password = ss[1];
            }
            catch
            {
                //If someone is trying to spoof, do it again.
                Response.Redirect("~/Default.aspx");
                return;
            }

            if (!LoginUser.Login(username, password))
            {
                Response.Redirect("~/Default.aspx");
                return;
            }

            Global.FindLoginLog(LoginUser.LoginID).session_id = this.Session.SessionID;
            this.Response.Redirect("DownloadBillReport.aspx?token=" + Common.CreateToken());
        }

        private void RemoveRedirCookie()
        {
            try
            {
                HttpCookie cookie = new HttpCookie("__LOGINCOOKIE__", "");
                cookie.Secure = true;
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ViewStateUserKey = Session.SessionID;
        }
    }
}